package com.anstudio.busfetion.util;

import com.anstudio.AnStudioUtil;
import com.anstudio.busfetion.BusFetionConfig;

import android.util.Log;

public class LocalUtil {

    private boolean DEBUG = BusFetionConfig.DEBUG;
    private String TAG = new String("LocalService");

    public LocalUtil () {
        super();

        if (DEBUG)
            Log.v(TAG, "Local service is constructed");
    }

    public boolean localSaveFav(String bus, String station) {

      if (DEBUG)
        Log.v(TAG, "add bus["
                     + bus
                     + "] and station["
                     + station
                     + "] to my favorite");

      AnStudioUtil.asWriteString2File(
            BusFetionConfig.BusFetionFavURI
          , bus + BusFetionConfig.CommonDelimiter
            + station + BusFetionConfig.CommonDelimiter
          , true);

        return true;
    }

    public String[] localLoadFav() {

      if (DEBUG)
        Log.v(TAG, "Load my favorite");

      String fav = AnStudioUtil.asReadFile2String(BusFetionConfig.BusFetionFavURI);
      return fav.split(BusFetionConfig.CommonDelimiter);
    }

    public boolean localDelFav(String bus, String station) {

      String[] myFav = localLoadFav();
      String res = "";

      if ((null == bus) && (null == station)) {
        if (DEBUG)
          Log.v(TAG, "How could this happen????");
        return true;
      } else if (null == bus) {
        if (DEBUG)
          Log.v(TAG, "Delete favorite by station[" + station + "]");

        for (int i = 1; i < myFav.length; i = i + 2) {
          if (myFav[i].equalsIgnoreCase(station)) {
            myFav[i - 1] = "";
            myFav[i] = "";
          }
        }
      } else if (null == station) {
        if (DEBUG)
          Log.v(TAG, "Delete favorite by bus[" + bus + "]");

        for (int i = 0; i < myFav.length; i = i + 2) {
          if (myFav[i].equalsIgnoreCase(bus)) {
            myFav[i] = "";
            myFav[i + 1] = "";
          }
        }

      } else {
        if (DEBUG)
          Log.v(TAG, "Delete favorite by bus["
                       + bus + "] and station["
                       + station + "]");

        for (int i = 0; i < myFav.length; i = i + 2) {
          if ((myFav[i].equalsIgnoreCase(bus))
             &&(myFav[i + 1].equalsIgnoreCase(station))){
            myFav[i] = "";
            myFav[i + 1] = "";
          }
        }
      }

      for (String tmp : myFav) {
        res += tmp;
        if ("" != tmp)
          res += BusFetionConfig.CommonDelimiter;
      }

      AnStudioUtil.asWriteString2File(
            BusFetionConfig.BusFetionFavURI
          , res
          , false);

        return true;
    }
}
